package cn.huiyunche.admin.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.huiyunche.admin.service.AdminCAccntBillService;
import cn.huiyunche.base.service.enums.AccBillStatusEnum;
import cn.huiyunche.base.service.enums.AccPaytypeEnum;
import cn.huiyunche.base.service.enums.AccTurnoverStatusEnum;
import cn.huiyunche.base.service.interfaces.CAccntTurnOverService;
import cn.huiyunche.base.service.mappers.CBillMapper;
import cn.huiyunche.base.service.mappers.ext.CBillViewMapper;
import cn.huiyunche.base.service.model.CBill;
import cn.huiyunche.base.service.model.CTurnover;
import cn.huiyunche.base.service.vo.CBillAdminVo;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.tools.basic.exceptions.BusinessException;

/**
 * 账单接口实现类
 * @author guanglulee
 *
 */
@Service
public class AdminCAccntBillServiceImpl implements AdminCAccntBillService {

	private static final Logger LOGGER = LoggerFactory.getLogger(AdminCAccntBillServiceImpl.class);

	@Autowired
	private CAccntTurnOverService cAccntTurnOverService = null;

	@Autowired
	private CBillMapper cBillMapper = null;

	@Autowired
	private CBillViewMapper cBillViewMapper = null;

	private CBillMapper getCBillMapper() {
		return this.cBillMapper;
	}

	private CAccntTurnOverService getCAccntTurnOverService() {
		return this.cAccntTurnOverService;
	}

	private CBillViewMapper getcBillViewMapper() {
		return cBillViewMapper;
	}

	/**
	 * 查询账单记录
	 * 		page
	 * 		userType
	 */
	@Override
	public Map<String, Object> getBills(PageVo page, CBillAdminVo bill, int userType) {
		LOGGER.info("select bills params page:{}, userType:{}.", page, userType);
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, Object> paramsMap = new HashMap<>();
			paramsMap.put("limitStart", page.getStartIndex());
			paramsMap.put("limitEnd", page.getPageSize());
			if(StringUtils.isNotBlank(page.getOrder())){
				paramsMap.put("orderByClause", page.getOrder());
			} else{
				paramsMap.put("orderByClause", " id DESC");
			}

			if(null != bill){
				paramsMap.put("userType", bill.getUserType());
				paramsMap.put("userName", bill.getUserName());
				paramsMap.put("phone", bill.getPhone());
				paramsMap.put("status", bill.getStatus());
				paramsMap.put("beginDate", bill.getBeginDate());
				paramsMap.put("endDate", bill.getEndDate());
			}

			page.setTotalRecord(this.getcBillViewMapper().countByConditions(paramsMap));
			List<CBillAdminVo> list = this.getcBillViewMapper().selectByConditions(paramsMap);

			map.put("page", page);
			map.put("cBills", list);
			/** List<CBill> cBills = new ArrayList<CBill>();

			 CBillExample example = new CBillExample();
			 example.setLimitStart(page.getStartIndex());
			 example.setLimitEnd(page.getPageSize());
			 if(StringUtils.isNoneBlank(example.getOrderByClause())){
			 example.setOrderByClause(example.getOrderByClause());
			 } else{
			 example.setOrderByClause("id DESC");
			 }
			 example.createCriteria().andUserTypeEqualTo(userType);

			 page.setTotalRecord(this.getCBillMapper().countByExample(example));
			 cBills = this.getCBillMapper().selectByExample(example);

			 LOGGER.info("select bills finish. params userType:{}.", userType);
			 map.put("cBills", cBills);
			 map.put("page", page); */
		} catch (Exception e) {
			LOGGER.error("select bills error : {}.", e);
			e.printStackTrace();
		}
		return map;
	}

	@Override
	public Result<String> settlementById(Long id) {
		Result<String> result = new Result<String>(true, null, "已支付，司机余额已扣除");
		try {
			// 查询账单 设置状态为 已支付
			CBill bill = this.getCBillMapper().selectByPrimaryKey(id);
			if(null == bill){
				result.setSuccess(false);
				result.setMessage("未查询到账单");
				return result;
			} else if(bill.getStatus() != AccBillStatusEnum.SETTLTMENT.getValue()){
				result.setSuccess(false);
				result.setMessage("该账单已结算，请务重复结算.");
				return result;
			}
			bill.setStatus(AccBillStatusEnum.DONE.getValue());
			this.getCBillMapper().updateByPrimaryKey(bill);

			// 添加账户流水记录 业务类型：提现 扣除金额
			List<CTurnover> list = new ArrayList<>();
			CTurnover cTurnover = new CTurnover();

			cTurnover.setPayType(AccPaytypeEnum.WITHDRAWAL.getValue());
			cTurnover.setStatus(AccTurnoverStatusEnum.DONE.getValue());
			cTurnover.setUserId(bill.getUserId());
			cTurnover.setUserName(bill.getUserName());
			cTurnover.setUserType(bill.getUserType());
			cTurnover.setOrderId(bill.getId());
			cTurnover.setOrderFee(bill.getAmount().abs().negate());
			cTurnover.setOrderActPay(bill.getAmount().abs().negate());
			cTurnover.setCreateTime(new Date());
			cTurnover.setUpdateTime(new Date());

			list.add(cTurnover);
			this.getCAccntTurnOverService().addDetailsAndLedger(list, 0);

			
			return result;
		} catch (Exception e) {
			LOGGER.error("settlement send by driver error : {}.", e);
			throw new BusinessException("系统异常");
		}
	}
	
	/**
	 * 人送项目司机 奖罚
	 * @param id
	 * @param money
	 * @return
	 */
	
	@Override
	public Result<String> rewardandpunish(Long id, BigDecimal money,String remark,String type) throws BusinessException{
		Result<String> result = new Result<String>(true, null, "已设置奖罚金额");
		// 查询账单 设置状态为 已支付
		CBill bill = this.getCBillMapper().selectByPrimaryKey(id);
		if(null == bill){
			result.setSuccess(false);
			result.setMessage("未查询到账单");
			return result;
		} else if(bill.getStatus() == AccBillStatusEnum.DONE.getValue()){
			result.setSuccess(false);
			result.setMessage("该账单已结算，不能继续设置奖罚金额.");
			return result;
		}
		this.getCBillMapper().updateByPrimaryKey(bill);

		// 添加账户流水记录 业务类型：提现 扣除金额
		List<CTurnover> list = new ArrayList<>();
		CTurnover cTurnover = new CTurnover();


		cTurnover.setStatus(AccTurnoverStatusEnum.DONE.getValue());
		cTurnover.setUserId(bill.getUserId());
		cTurnover.setUserName(bill.getUserName());
		cTurnover.setUserType(bill.getUserType());
		cTurnover.setOrderId(bill.getId());
		cTurnover.setBillId(bill.getId());
		if("0".equals(type)){
			cTurnover.setPayType(AccPaytypeEnum.REWARD.getValue());
			cTurnover.setOrderFee(money);
			cTurnover.setOrderActPay(money);
			bill.setAmount(bill.getAmount().add(money));
		}else{
			cTurnover.setPayType(AccPaytypeEnum.PUNISH.getValue());
			cTurnover.setOrderFee(money.abs().negate());
			cTurnover.setOrderActPay(money.abs().negate());
			if(bill.getAmount().compareTo(money) != -1) {
				bill.setAmount(bill.getAmount().subtract(money));
			} else {
				throw new BusinessException("罚款金额不能大于账单金额");
			}
		}
		
		cTurnover.setCreateTime(new Date());
		cTurnover.setUpdateTime(new Date());
		cTurnover.setRemark(remark);
		list.add(cTurnover);
		try {
			//新增流水
			this.getCAccntTurnOverService().addDetailsAndLedger(list, 0);
			//更新账单
			this.getCBillMapper().updateByPrimaryKeySelective(bill);
		} catch (Exception e) {
			LOGGER.error("update trunover error: {}", e);
			throw new BusinessException("系统异常");
		}
		return result;
	}
}